const {
	Service
} = require('uni-cloud-router')
module.exports = class OrderService extends Service {
	constructor(ctx) {
		super(ctx)
		this.collection = this.db.collection('tian-mall-orders')
	}
	async setDeliver({
		id,
		goods_id,
		sku_id,
		number,
		company,
		code
	}, adminUser) {
		//查询订单
		let order = await this.getOrderById(id);
		if (!order) {
			return {
				code: -1,
				message: "订单不存在"
			}
		}
		/* let goods = order.goods;
		if (goods_id || sku_id) {
			//单品发货
			goods = goods.filter(g => {
				return g.goods_id == goods_id && (!sku_id || sku_id == g.sku_id);
			})
		} */
		const cmd = this.db.command;
		let delivers = order.delivers;
		console.log("order.delivers", order.delivers)
		if (!delivers) {
			delivers = [];
		} else if (order.goods.length == 1) {
			delivers = [];
		} else {
			//push或者更新
			let oldIndex = delivers.findIndex(e => e.goods_id == goods_id && (!sku_id || e.sku_id == sku_id));
			console.log("oldIndex", oldIndex)
			if (oldIndex != -1) {
				delivers.splice(oldIndex, 1)
			}
		}
		delivers.push({
			goods_id,
			sku_id,
			number,
			company,
			code
		})
		console.log("order.delivers", order.delivers)
		return await this.collection.doc(id).update({
			state: 2,
			delivers: delivers,
			logs: cmd.push({
				adminUser,
				time: Date.now(),
				title: "订单发货"
			})
		})
	}
	/**
	 * 买家确定收货，付款金额，全部到达商家账户goods_total_fee
	 * @param {Object} order
	 */
	async finish(order) {
		const cmd = this.db.command;
		//更新订单为已收货3		//定时器更新返利
		let rebate_last_time = this.ctx.getConfigs.config("user.rebate_last_time");
		let res = await this.collection.doc(order._id).update({
			state: 3,
			rebate_state: 1,
			rebate_last_time: Date.now() + rebate_last_time * 1000,
			logs: cmd.push({
				time: Date.now(),
				title: "确定收货"
			})
		});
		return res;
	}

	async getOrderById(id) {
		let {
			data: orderData
		} = await this.collection.doc(id).get();
		if (orderData.length == 0) {
			return false;
		}
		return orderData[0];
	}

	/**
	 * @param {Object} ids
	 * @param {Object} uid
	 */
	async getStatitics(uid) {}

	/**
	 * 定时器,1：确定收货订单，佣金到账
	 */
	async timer() {
		await this.rebateTimer();
		await this.groupBuyingTimer();
	}

	/**
	 * 拼团订单，1小时之前(随机1-8小时)，自动处理
	 */
	async groupBuyingTimer() {
		let limit = 100;
		const cmd = this.db.command;
		let collection = this.db.collection('opendb-mall-goods-group-buying');
		let hour = parseInt(Math.random() * 8);
		let {
			data
		} = await collection.where({
			state: 1,
			end_time: cmd.lte(Date.now() + 3600 * hour * 1000)
		}).limit(limit).get();
		if (data.length == 0) {
			console.log("没有待处理的拼单")
			return;
		}
		let ids = data.map(e => e._id);
		//自动完成拼单
		await collection.where({
			_id: cmd.in(ids)
		}).update({
			state: 2
		})
		//更新订单状态
		let groupid = data.map(e => e.group_id);
		await this.collection.where({
			"group_buying.group_buying_id": cmd.in(groupid),
			state: 1
		}).update({
			group_buying: {
				state: 2,
				finish_time: Date.now()
			}
		})
		if (data.length == limit) {
			console.log("处理第二批拼单")
			//递归处理
			await this.groupBuyingTimer();
		}
	}

	/**
	 * 订单返利
	 */
	async rebateTimer() {
		const cmd = this.db.command;
		let {
			data
		} = await this.collection.where({
			rebates: cmd.exists(true),
			rebate_state: 1,
			rebate_last_time: cmd.lte(Date.now())
		}).field({
			id: 1,
			body: 1,
			rebates: 1
		}).limit(10).get();
		console.log("查询到待返利订单", data.length)
		if (data.length > 0) {
			let uids = [];
			for (let order of data) {
				//更新订单状态，防止再次触发
				await this.collection.doc(order._id).update({
					rebate_state: 2,
					rebate_process_time: Date.now()
				})
				console.log("更新订单状态完成", order._id)
				for (let rebate of order.rebates) {
					//推荐人，自己等人员
					if (rebate.type == "user") {
						if (rebate.money) {
							console.log("订单返现金")
							//uid, amount, comment
							await this.service.user.user.editBalance(rebate.id, rebate.money, "购买商品返利", 0, {
								_id: order._id,
								id: order.id,
								type: "mall",
								body: order.body,
							})
						}
						if (rebate.score) {
							console.log("订单返积分")
							// uid, amount, comment, level = 0, log
							await this.service.user.user.editScore(rebate.id, rebate.money, "购买商品积分", 0, {
								_id: order._id,
								id: order.id,
								type: "mall",
								body: order.body,
							})
						}
						if (uids.indexOf(rebate.id) == -1) {
							uids.push(rebate.id)
						}
					} else {
						//其他类型的统计
						await this.service.system.app.setScoreDayStatistics(rebate.amount,
							rebate.type, order.today);
					}
				}
			}
		}
	}
}
